Capture Image and Save in Local

Capture and save an image in local using webcam

Description

This snippet of code will allow you to capture images from your webcam and save in your local system.

Requirements

$ pip install opencv-python

Steps To Execution

  • Fork this repo and navigate to Capture Image and Save in Local folder
  • Run capture_img.py using $ python capture_img.py
  • A webcam window is displayed. Adjust the desired object in position and press the Spacebar key to capture.
  • Check the command prompt for a success or failure message.
  • If successful, you will see an image with name opencv_frame_0.png in the same directory as the python script.
  • Press the Escape key to close the webcam window.

Code Output

How the webcam window will look How the directory structure looks

Source Code: capture_img.py

import cv2

cam = cv2.VideoCapture(0)

img_counter = 0

while True:
    ret, frame = cam.read()
    if not ret:
        print("Failed to grab frame")
        break
    cv2.imshow("Capture Image using webcam and save in local storage!", frame)

    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break
    elif k%256 == 32:
        # SPACE pressed
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_name))
        img_counter += 1

cam.release()

cv2.destroyAllWindows()